package com.smart.speaker.websocket;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.smart.speaker.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

@Slf4j
public class MessageHandler implements Runnable {

    private final BlockingQueue<Object> queue;
    private final WebSocketSession session;
    private volatile boolean isRunning = true;

    public MessageHandler(WebSocketSession session) {
        this.queue = new ArrayBlockingQueue<>(20);
        this.session = session;
        Thread.ofVirtual().start(this);
    }

    @Override
    public void run() {
       while (isRunning) {
           try {
               Object message = queue.take();
               if (message instanceof String) {
                   session.sendMessage(new TextMessage((String) message));
               } else if (message instanceof byte[]) {
                   session.sendMessage(new BinaryMessage((byte[]) message));
               } else {
                   log.error("未知的消息类型: {}", message.getClass().getName());
               }
           } catch (Exception e) {
               log.error("发送消息时发生异常 - SessionId: {}", session.getId(), e);
           }
       }
    }

    public void sendMessage(Object message) {
        try {
            queue.put(message);
        } catch (InterruptedException e) {
            log.error("消息队列put时发生异常 - SessionId: {}", session.getId());
        }
    }

    public void sendMessage(String type, String state, String message) {
        if (session == null || !session.isOpen()) {
            log.warn("无法发送消息 - 会话已关闭或为null");
            return;
        }
        try {
            ObjectNode response = JsonUtils.createObjectNode();
            response.put("type", type);
            if (state != null) {
                response.put("state", state);
            }
            if (message != null) {
                response.put("text", message);
            }
            String jsonMessage = response.toString();
            sendMessage(jsonMessage);
        } catch (Exception e) {
            log.error("添加消息时发生异常 - SessionId: {}", session.getId(), e);
        }
    }

    public void close() {
        isRunning = false;
    }
}
